# 客户端
import sys
import json
import datetime
import logging
import pandas as pd
import jqktrader

file_path = 'gb.log'  #操作日志的记录
logging.basicConfig(filename=file_path,level=logging.INFO)

#需要配置的参数
EXE_PATH = r'C:\同花顺软件\同花顺\xiadan.exe'  
Tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  #可选参数
#需要配置的参数 结束


# 初始化同花顺客户端
#user = easytrader.use('ths')
user = jqktrader.use()
user.connect(exe_path=EXE_PATH, tesseract_cmd=Tesseract_cmd)
print(user)
print('success')



def auto_buy(stock, price, amount):
    #1.刷新数据
    user.refresh()
    result = user.buy(stock, price=price, amount=amount)
    return result

def auto_sell(stock, price, amount):
    #1.刷新数据
    user.refresh()
    result = user.sell(stock, price=price, amount=amount)
    return result
    
def remote_close():
    import subprocess
    result = subprocess.run('1.bat', shell=True, capture_output=True, text=True)
    print(result.stdout)
    
def handle_gp(args):
    #print(args)
    
    #return
    try:
        s = args[0]
        dict = json.loads(s)
        dict = dict[0]
        print(dict)

       
        ss = dict
        token = ss['token']
        #print(token)
        
        if ss:
            #print(ss['action'])
            
            if ss['action'] == 'buy':
                if token == 123:
                    stock = ss['zqdm'][:6]
                    num = ss['qty']
                    strategy = ss['strategy']
                    trade_time = ss['trade_time']
                    now_time = ss['time']
                    price = ss['price']

                    logging.info(f'%s %s %s %s %s %s %s' % (stock, num, 'buy', price, trade_time, strategy, now_time))
                    auto_buy(stock,price, num)
            elif ss['action'] == 'sell':
                if token == 123:
                    stock = ss['zqdm'][:6]
                    num = ss['qty']
                    strategy = ss['strategy']
                    trade_time = ss['trade_time']
                    now_time = ss['time']
                    price = ss['price']
                    
                    logging.info(f'%s %s %s %s %s %s %s' % (stock, num, 'sell', price, trade_time, strategy, now_time))
                    auto_sell(stock,price, num)
            
        #     print("recv params:")
        #     for i, arg in enumerate(args, 1):
        #         print(f"params {i}: {arg}")
    except Exception as e:
        print('error')
        logging.info(f'%s %s' % (e, now_time))
        print(e)
    
#获取当前时间
def get_now():
    from datetime import datetime
    current_datetime = datetime.now()
    formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_datetime

def main():
    # sys.argv[0] 是脚本名称
    # sys.argv[1:] 是传递的参数
    args = sys.argv[1:]
    if not args:
        print("Usage: python script.py [arg1] [arg2] ...")
        return
    #do it
    handle_gp(args)

if __name__ == "__main__":
    main()